import React, { useEffect } from 'react';

function append(content, container = 'content', tagname = 'p') {
  const tag = document.createElement(tagname);
  const text = document.createTextNode(content);
  tag.appendChild(text);
  document.getElementById(container).appendChild(tag);
}

function proxyDemo() {
  const person = {
    name: 'zhangsan',
    age: 20,
  };

  const personProxy = new Proxy(person, {
    get(target, property) {
      return property in target ? target[property] : 'default';
    },
    set(target, property, value) {
      if (property === 'age') {
        if (!Number.isInteger(value)) {
          throw new TypeError(`${value} is not an int number`);
        }
      }
      Object.assign(target, {
        [property]: value,
      });
    },
    deleteProperty(target, property) {
      console.log('delete', property);
      // eslint-disable-next-line no-param-reassign
      delete target[property];
    },
  });

  // personProxy.age = '23424'; // TypeError
  // personProxy.gender = true;
  delete personProxy.age;

  append(personProxy.name);
  append(personProxy);
}

export default function Async() {
  useEffect(proxyDemo, null);

  return (
    <div id="content">
      <p>proxy</p>
    </div>
  );
}
